import React, { useState, useEffect } from 'react';
import { FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, Dimensions } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import { Feather } from '@expo/vector-icons';
import { Entypo } from '@expo/vector-icons';
import { MaterialIcons } from '@expo/vector-icons';
import { baseAvatarUrl } from '../context/AuthProvider';
import { useAuth, baseURL } from '../context/AuthProvider';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from '../api/axios';
import { useFocusEffect } from '@react-navigation/native';

const add = (m) => { return m < 10 ? '0' + m : m }
//将时间戳转为普通格式
const fortime = (shijianchuo) => {
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add(m) + '-' + add(d) + ' ' + add(h) + ':' + add(mm) + ':' + add(s);
}

const getH = (uri) => {
    // console.log(uri);
    let img = Image.resolveAssetSource(require('../../images/mine/topbg.jpg'));
    let height = Dimensions.get('window').width / img.width * img.height
    return height
}
const getW = () => {
    let img = Image.resolveAssetSource(require('../../images/mine/avatar.jpg'));
    // console.log(img);
    let width = getH() * 0.56 / img.height * img.width
    return width
}
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                padding: 2,
                ...style
            }
        }>
            <Text style={{ color: color }}>{children}</Text>
        </TouchableOpacity>
    )
}
const Mine = ({ navigation }) => {
    const { navigate } = navigation
    const { user } = useAuth()
    const { setUser } = useAuth()
    const [mycrops, setMyCrops] = useState(0)
    const [nowgrow, setNowgrow] = useState(0)
    const [mynews, setMynews] = useState(0)
    const [mysign, setMysign] = useState(0)
    const [msign, setMsign] = useState(0)
    const [lastdate, setLastdate] = useState('')
    // const [signday, set]
    console.log(22222);
    useEffect(() => {
        let str = fortime(1684045537530)
        let s = str.split(' ')
        console.log(fortime(1684045537530));
        console.log(s[0]);
        if (user) {
            axios.post('/crop/getmycrops', { userid: user.userid }).then(res => {
                // console.log(res);
                setMyCrops(res.data.length)
            })
            axios.post('/crop/getnowgrow', { userid: user.userid }).then(res => {
                setNowgrow(res.nowgrow)
            })
            axios.post('/news/getmynews', { userid: user.userid }).then(res => {
                setMynews(res.data.length)
            })
            axios.post('/sign/getmysign', { userid: user.userid }).then(res => {
                console.log(res.data);
                setMsign(res.data[0].date)
                setLastdate(res.data[0].date)
                setMysign(res.data.length)
            })
        }
    }, [])
    useFocusEffect(React.useCallback(() => {
        if (user) {
            axios.post('/news/getmynews', { userid: user.userid })
                .then(res => {
                    setMynews(res.data.length)
                })
            axios.post('/crop/getnowgrow', { userid: user.userid }).then(res => {
                setNowgrow(res.nowgrow)
            })
            axios.post('/sign/getmysign', { userid: user.userid }).then(res => {
                console.log(res.data);
                setMsign(res.data[0].date)
                setLastdate(res.data[0].date)
                setMysign(res.data.length)
            })
        }
    }, []))

    const sign = () => {
        let nows = fortime(new Date().getTime());
        let now = nows.split(' ')
        if (user) {
            if (now[0] == lastdate) {
                navigation.navigate('sign')
            } else {
                axios.post('/sign/addmysign', { userid: user.userid, date: now[0] }).then(res => {
                    navigation.navigate('sign')
                    setMsign(sign + 1)
                })
            }
        } else {
            alert("请先登录")
        }
    }
    return <View>
        <ImageBackground source={require('../../images/mine/topbg.jpg')} style={styles.topBackImg}>
            {user ?
                <View style={styles.avaNickSign}>
                    <Image source={user.avatar ? { uri: baseURL + user.avatar } : require('../../images/mine/1.jpg')} style={styles.topImg}></Image>
                    <View style={styles.nickSign}>
                        <Text style={{ margin: '1%', fontSize: 15.6 }}>{user.nickname}</Text>
                        <Text>签名：{user.signature ? user.signature : '这个人很神秘，还没有签名哦'}</Text>
                    </View>
                </View>
                :
                <View style={styles.avaNickSign}>
                    <Image source={require('../../images/mine/1.jpg')} style={styles.topImg}></Image>
                    <View style={styles.nickSign}>
                        <Text style={{ margin: '1%', fontSize: 15.6 }} onPress={() => navigate('login')}>未登录用户，点击登录</Text>
                        <Text>签名：无</Text>
                    </View>

                </View>
            }

            <View style={{ marginRight: '2%' }}>
                <Btn style={{ width: '100%', marginTop: '80%', backgroundColor: '#A0D377' }} color={'#fff'}
                    onPress={sign}>
                    签到</Btn>
            </View>
        </ImageBackground >
        <View style={styles.cal}>
            <Text style={{ marginLeft: '4%' }}>种植日历</Text>
            <View style={styles.calCon} onStartShouldSetResponder={() => { if (user) { navigation.navigate('nowgrow') } else { alert("请先登录") } }}>
                <View style={styles.calOne}>
                    <Text style={{ fontSize: 13 }} onPress={() => { if (user) { navigation.navigate('nowgrow') } else { alert("请先登录") } }}>正在种植</Text>
                    <Text style={{ marginTop: '20%', fontSize: 16 }}>{user ? nowgrow : 0}</Text>
                    {/* <Text style={{ marginTop: '20%', fontSize: 16 }}>0</Text> */}
                </View>
                <View style={styles.calOne} >
                    <Text style={{ fontSize: 13 }}>成功收获</Text>
                    <Text style={{ marginTop: '20%', fontSize: 16 }}>{user ? mycrops - nowgrow : 0}</Text>
                    {/* <Text style={{ marginTop: '20%', fontSize: 16 }}>0</Text> */}
                </View>
                <View style={styles.calOne} onStartShouldSetResponder={() => { if (user) { navigation.navigate('mynews') } else { alert("请先登录") } }}>
                    <Text style={{ fontSize: 13 }} onPress={() => { if (user) { navigation.navigate('mynews') } else { alert("请先登录") } }}>发布动态</Text>
                    <Text style={{ marginTop: '20%', fontSize: 16 }}>{user ? mynews : 0}</Text>
                </View>
                <View style={styles.calOne}>
                    <Text style={{ fontSize: 13 }}>签到天数</Text>
                    <Text style={{ marginTop: '20%', fontSize: 16 }}>{user ? mysign : 0}</Text>
                </View>
            </View>
        </View>
        <TouchableOpacity style={styles.miniCon} onPress={() => { if (user) { navigation.navigate('mineNews') } else { alert("请先登录") } }} activeOpacity={0.6}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Feather name="aperture" size={22} color="black" />
                <Text style={{ marginLeft: '8%' }}>论坛圈子</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>
        <TouchableOpacity style={styles.miniCon} onPress={() => { if (user) { navigation.navigate('coin') } else { alert("请先登录") } }} activeOpacity={0.6}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <AntDesign name="wallet" size={22} color="black" />
                <Text style={{ marginLeft: '8%' }}>我的硬币</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>
        <TouchableOpacity style={[styles.miniCon, styles.miniCon1]} activeOpacity={0.6} onPress={() => { if (user) { navigation.navigate('collection', { userid: user.userid }) } else { alert("请先登录") } }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <AntDesign name="staro" size={24} color="black" />
                <Text style={{ marginLeft: '8%' }}>我的收藏</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>
        <TouchableOpacity style={styles.miniCon} activeOpacity={0.6} onPress={() => { if (user) { navigation.navigate('paylist', { userid: user.userid }) } else { alert("请先登录") } }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <MaterialIcons name="list-alt" size={24} color="black" />
                <Text style={{ marginLeft: '8%' }}>我的订单</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>

        <TouchableOpacity style={[styles.miniCon, styles.miniCon1]} onPress={() => { if (user) { navigation.navigate('accounts') } else { alert("请先登录") } }} activeOpacity={0.6}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <AntDesign name="edit" size={24} color="black" />
                <Text style={{ marginLeft: '8%' }}>修改用户信息</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>
        <TouchableOpacity style={styles.miniCon} activeOpacity={0.6} onPress={() => navigation.navigate('setting')}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <AntDesign name="setting" size={24} color="black" />
                <Text style={{ marginLeft: '8%' }}>设置</Text>
            </View>
            <Entypo name="chevron-thin-right" size={20} color="black" />
        </TouchableOpacity>
    </View >
}

const styles = StyleSheet.create({
    container: {
        marginHorizontal: 15
    },
    topBackImg: {
        width: Dimensions.get('window').width,
        height: getH('../../images/mine/topbg.jpg'),
        flexDirection: 'row',
        // alignItems: 'center',
        justifyContent: 'space-between'
    },
    avaNickSign: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '75%',
        // justifyContent: 'space-between'
    },
    topImg: {
        height: '56%',
        width: getW('../../images/mine/avatar.jpg'),
        borderRadius: 50,
        borderWidth: 4,
        borderColor: '#fff',
        marginLeft: '8%'
    },
    nickSign: {
        // alignItems: 'center'
        marginLeft: '5%'
    },
    cal: {
        backgroundColor: '#fff',
        margin: '5%',
        marginTop: '-2%',
        paddingTop: '2%',
        borderRadius: 8,
        borderColor: '#BBBBBB',
        borderWidth: 1
    },
    calCon: {
        justifyContent: 'space-around',
        flexDirection: 'row',
        marginTop: '4%',
        marginBottom: '5%'
    },
    calOne: {
        alignItems: 'center'
    },
    miniCon: {
        backgroundColor: '#fff',
        marginLeft: '5%',
        marginRight: '5%',
        borderColor: '#BBBBBB',
        borderWidth: 0.5,
        alignItems: 'center',
        padding: '3%',
        justifyContent: 'space-between',
        flexDirection: 'row',
    },
    miniCon1: {
        marginTop: '5%'
    },
});

export default Mine;